package xyz.chaobei.redis.impl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;
import xyz.chaobei.redis.model.User;
import xyz.chaobei.redis.repository.RedisRepository;

@Repository
public class RedisRepositoryImpl implements RedisRepository<User, Integer> {

    private RedisTemplate<String, Object> redisTemplate;
    private ValueOperations<String, Object> valueOperations;

    private final String keyPrefix = "User";

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.valueOperations = this.redisTemplate.opsForValue();
    }

    @Override
    public void save(User user) {
        valueOperations.set(keyPrefix + user.getId(), user);
    }

    @Override
    public User findById(Integer integer) {
        JSONObject object = (JSONObject) valueOperations.get(keyPrefix + integer);
        return object.toJavaObject(User.class);
    }

    @Override
    public Boolean deleteById(Integer integer) {
        return valueOperations.getOperations().delete(keyPrefix + integer);
    }

    @Override
    public void update(User user) {
        valueOperations.set(keyPrefix + user.getId(), user);
    }
}
